<template>
  <div class="page-miH page-bgBack">
    <div class="xq-form-wrapper" style="padding:24px;">
      <span class="empInfoNames" @click="$router.go(-1)"> <a-icon type="left" />返回 </span>
      <div class="detailTitle">{{ empInfoName }} 的 {{ month2 }} 月打卡记录</div>
      <a-row type="flex" justify="space-between" align="middle">
        <a-col>
          <span class="shouldDayCount"> {{ month2 }}月应打卡天数{{ shouldDayCount }}天 </span>
          （正常天数{{ entityCount }}天）
        </a-col>
        <a-col>
          <a-button type="primary" @click="download">
            导出个人月报表
          </a-button>
        </a-col>
      </a-row>
      <a-spin :spinning="spinning" class="xq-form-content" style="margin-top: 24px">
        <XqTable
          :customize="FormJson['config']['table']['customize']"
          :scroll="{ x: columns.length * 150 }"
          :pagination="false"
          :dataSource="tableData"
          :columns="columns"
          class="xq-form-content-table"
        >
          <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
            <span :key="index">
              {{ col.customTitle }}
            </span>
          </template>
          <!-- eslint-disable-next-line prettier/prettier -->
          <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
            <div v-if="col.dataIndex === 'arriveOne.arriveTime' || col.dataIndex === 'arriveTwo.arriveTime'" :key="index">
              <span :class="record[col.dataIndex.split('.')[0]].arriveStatus === '正常' ? '' : 'errorColor'">
                {{ text ? moment(text).format("HH:mm:ss") : "--" }}
              </span>
              <span :class="record[col.dataIndex.split('.')[0]].arriveStatus === '正常' ? '' : 'errorColor'">
                （{{ record[col.dataIndex.split(".")[0]].arriveStatus ? record[col.dataIndex.split(".")[0]].arriveStatus : "--" }}）
              </span>
            </div>
            <div v-else-if="col.dataIndex === 'arriveOne.arrivePlace' || col.dataIndex === 'arriveTwo.arrivePlace'" :key="index">
              <span :class="record[col.dataIndex.split('.')[0]].rangeState === '1' ? '' : 'errorColor'">{{ text ? text : "--" }}</span>
            </div>
            <div v-else-if="col.dataIndex === 'leaveOne.leaveTime' || col.dataIndex === 'leaveTwo.leaveTime'" :key="index">
              <span :class="record[col.dataIndex.split('.')[0]].leaveStatus === '正常' ? '' : 'errorColor'">
                {{ text ? moment(text).format("HH:mm:ss") : "--" }}
              </span>
              <span :class="record[col.dataIndex.split('.')[0]].leaveStatus === '正常' ? '' : 'errorColor'">
                （{{ record[col.dataIndex.split(".")[0]].leaveStatus ? record[col.dataIndex.split(".")[0]].leaveStatus : "--" }}）
              </span>
            </div>
            <div v-else-if="col.dataIndex === 'leaveOne.leavePlace' || col.dataIndex === 'leaveTwo.leavePlace'" :key="index">
              <span :class="record[col.dataIndex.split('.')[0]].rangeState === '1' ? '' : 'errorColor'">{{ text ? text : "--" }}</span>
            </div>
            <span v-else-if="col.dataIndex === 'tableAction'" :key="index">
              <a @click="enterDetail(record)">详情</a>
            </span>
            <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
          </template>
        </XqTable>
        <div class="xq-form-content-pagination">
          <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
          <a-pagination
            v-model="pageNo"
            :page-size="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :page-size-options="['10', '20', '50', '100']"
            @change="onPageChange"
            @showSizeChange="onPageSizeChange"
          />
        </div>
      </a-spin>
    </div>
    <msg :visible.sync="visibleMsg" :jsonData="jsonData" @onUpdate="getCheckStaffMonth" />
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});

import { checkStaffMonth } from "@/api/check/checkCard";
import msg from "../../component/msg";

export default {
  mixins: [curdMixin],
  components: {
    msg
  },
  data() {
    return {
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      empInfoName: "",
      year: "",
      month: "",
      month2: "",
      shouldDayCount: "",
      entityCount: "",
      visibleMsg: false,
      jsonData: {}
    };
  },

  created() {
    this.year = this.$route.query.year;
    this.empInfoName = this.$route.query.empInfoName;
    const m = this.$route.query.month.split("");
    let m2 = "";
    if (m[0] === "0") m2 = m[1];
    if (m[0] === "1") this.$route.query.month;
    this.month2 = m2;
    this.month = this.$route.query.month;
    this.getCheckStaffMonth();
  },

  methods: {
    enterDetail(record) {
      this.jsonData = record;
      this.jsonData.empInfoName = this.empInfoName;
      this.visibleMsg = true;
    },
    download() {
      const token = this.$store.state.auth.token;
      const params = {
        companyId: this.$store.state.hr.companyId,
        empInfoId: this.$route.query.empInfoId,
        year: this.year,
        month: this.month
      };
      axios({
        url: `/hr/api/v1/attendPunchRecords/exportAttendMonth`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${this.empInfoName}_` + "个人月报表" + ".xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    },
    async getCheckStaffMonth() {
      try {
        this.spinning = true;
        const { data } = await checkStaffMonth({
          companyId: this.$store.state.hr.companyId,
          empInfoId: this.$route.query.empInfoId,
          year: this.year,
          month: this.month,
          pageNo: this.pageNo,
          pageSize: this.pageSize
        });
        this.tableData = data.entities;
        this.total = data.entityCount;
        this.tableData.forEach(item => {
          const arrive = {
            arriveTime: null,
            arrivePlace: null,
            rangeState: null
          };
          const leave = {
            leaveTime: null,
            leavePlace: null,
            rangeState: null
          };
          item.arriveOne = item.arriveOne || arrive;
          item.leaveOne = item.leaveOne || leave;
          item.arriveTwo = item.arriveTwo || arrive;
          item.leaveTwo = item.leaveTwo || leave;
        });
        this.shouldDayCount = this.tableData[0].shouldDayCount;
        this.entityCount = this.tableData[0].count;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    onPageChange(page) {
      this.pageNo = page;
      this.getCheckStaffMonth();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getCheckStaffMonth();
    }
  }
};
</script>
<style lang="scss" scoped>
.shouldDayCount {
  font-weight: 600;
}
.empInfoNames {
  cursor: pointer;
  width: 45px;
}
.empInfoName {
  font-size: 18px;
  font-weight: 500;
  padding-bottom: 5px;
}
.details {
  color: var(--primary);
  cursor: pointer;
}
.errorColor {
  color: var(--primary);
}
.noClickStatus {
  color: #999 !important;
}
.clickStatus {
  color: var(--primary);
  cursor: pointer;
}
.c_title {
  height: 80px;
  line-height: 80px;
}
.detailTitle {
  text-align: center;
  font-weight: 500;
  font-size: 16px;
  padding-bottom: 20px;
}
.avator {
  border-radius: 100;
}
.info {
  padding-top: 5px;
}
</style>
